import http from './http.js';

class Order {
  constructor(data) {
    this.order_id = data.order_id;
    this.store_id = data.store_id;
    this.customer_id = data.customer_id;
    this.items = data.items;
    this.total_amount = data.total_amount;
    this.status = data.status || 'pending';
    this.payment_method = data.payment_method;
    this.remarks = data.remarks;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  static fromApi(data) {
    return new Order({
      order_id: data.order_id,
      store_id: data.store_id,
      customer_id: data.customer_id,
      items: data.items,
      total_amount: data.total_amount,
      status: data.status,
      payment_method: data.payment_method,
      remarks: data.remarks,
      created_at: data.created_at,
      updated_at: data.updated_at
    });
  }

  toApi() {
    return {
      store_id: this.store_id,
      customer_id: this.customer_id,
      items: this.items,
      total_amount: this.total_amount,
      remarks: this.remarks
    };
  }
}

export default {
  /**
   * 创建订单
   * @param {Object} orderData 订单数据
   * @returns {Promise<Order>}
   */
  async create(orderData) {
    try {
      const response = await http.post('/orders/', orderData);
      return response.data;
    } catch (error) {
      console.error('创建订单失败:', error);
      throw error;
    }
  },

  /**
   * 获取订单详情
   * @param {string} orderId 订单ID
   * @returns {Promise<Order>}
   */
  async getById(orderId) {
    try {
      const response = await http.get(`/orders/${orderId}`);
      return Order.fromApi(response.data);
    } catch (error) {
      console.error('获取订单详情失败:', error);
      throw error;
    }
  },

  /**
   * 更新订单
   * @param {string} orderId 订单ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<Order>}
   */
  async update(orderId, updateData) {
    try {
      const response = await http.put(`/orders/${orderId}`, updateData);
      return response.data;
    } catch (error) {
      console.error('更新订单失败:', error);
      throw error;
    }
  },

  /**
   * 删除订单(软删除)
   * @param {string} orderId 订单ID
   * @returns {Promise<void>}
   */
  async delete(orderId) {
    try {
      await http.delete(`/orders/${orderId}`);
    } catch (error) {
      console.error('删除订单失败:', error);
      throw error;
    }
  },

   /**
   * 获取订单列表
   * @param {Object} params 查询参数
   * @returns {Promise<{data: Order[]}>}
   */
   async getList(params = {}) {
    try {
      const response = await http.get('/orders', { ...params });
      return response.data;
    } catch (error) {
      console.error('获取订单列表失败:', error);
      throw error;
    }
  }
};